<template>
  <!-- 注册 -->
   <div class="register-view">
    <!-- 调用导航条 -->
        <base-nav :show-right="false" title="注册"></base-nav>
        <!-- 调用表单组件 -->
        <van-form ref="vanRegisterForm">
         <!-- 输入框 -->
        <van-cell-group inset>
            <van-field
            v-model="username"
            name="用户名"
            label="用户名"
            placeholder="3-12位字母数字组成"
            :rules="rulesUsername"
            />
            <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="6-12位数字组成"
            :rules="rulesPassword"
            autocomplete 
            />
            <van-field
            v-model="chackpassword"
            type="password"
            name="确认密码"
            label="确认密码"
            placeholder="确认密码"
            :rules="ruleschackpassword"
            
            />
        </van-cell-group>
        <div style="margin: 16px;">
          <!-- 注册按钮 -->
            <van-button style="border-radius: 0px;" round block type="primary" @click="Register">
                 注册
            </van-button>
        </div>
        </van-form>
   </div>
  
</template>

<script setup lang="ts">
  import API from './../api'

  let router = useRouter();
  let username = ref('');
  let password = ref('');
  let chackpassword = ref('');
  let vanRegisterForm = ref(null);
  


  
  //校验用户名
  let checkUsername = async (val:string) =>{
    if(!(/^[a-zA-Z0-9_]{3,12}$/g.test(val))){
        console.log("11");
        
        rulesUsername[0].message = '用户名必须为3-12位数字字母下划线组成';
        return false;
    };
    
    //请求用户名是否可用
    let even = await API.getUserData('/api_user',{
        status: 'check',
        username : username.value
    });
    console.log(even.code)
    if(even.code != 0){
        showFailToast('用户已存在');
        rulesUsername[0].message = '用户名已存在';
        return false;
    };

    return true;

  };

    //校验用户名
    let rulesUsername = [{
      required: true,
      validator: checkUsername,
      message: '' ,
      trigger: 'onBlur'
    }];
    // 校验密码
    let rulesPassword = [{ 
      required: true,
      validator: (val:string) => /^[a-zA-Z0-9]{6,12}$/g.test(val),
      message: '密码必须为6-12位数字组成' ,
      trigger: 'onChange'
    }];

    let ruleschackpassword = [{
      required: true,
      validator: (val:string) => password.value == chackpassword.value,
      message: '密码不相同' ,
      trigger: 'onChange'
    }];


  
  //注册方法
  async function Register(){
  
    await vanRegisterForm.value.validate();
    // console.log(vanRegisterForm.value.validate());

    //请求注册方法
    let even = await API.getUserData('/api_user',{
        status: 'register',
		username: username.value,
		password: password.value
    });
    // 注册失败提示
    if(even.code != 0){
        showFailToast(`注册失败${even.msg}`);
    };

    showSuccessToast(`注册成功`);
    // 跳转到登录
    router.push('/login');
    
  };
</script>

<style>

</style>